<template>
  <!-- 添加或修改商品信息对话框 -->
  <el-dialog
    :title="title"
    :visible="visiable"
    width="900px"
    append-to-body
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="cancel"
  >
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="100px"
      style="padding-right: 20px"
    >
      <el-form-item label="商品编号" prop="goodsCode">
        <el-input v-model="form.goodsCode" placeholder="请输入商品编号" />
      </el-form-item>
      <el-form-item label="货品名称" prop="goodsName">
        <el-input v-model="form.goodsName" placeholder="请输入货品名称" />
      </el-form-item>
      <el-form-item label="商品类别" prop="productCategoryId">
        <!-- <el-cascader
          v-model="form.productCategoryId"
          placeholder="请选择商品类别"
          :options="categoryList"
          :props="{ value: 'id', label: 'categoryName' }"
          clearable
        ></el-cascader> -->
        <treeselect
          v-model="form.productCategoryId"
          :options="categoryList"
          :normalizer="normalizer"
          placeholder="选择父级分类"
        />
      </el-form-item>
      <el-form-item label="商品价格" prop="goodsPrice">
        <el-input-number
          v-model="form.goodsPrice"
          :precision="2"
          :step="0.1"
          :min="0"
          placeholder="请输入商品价格"
        />
      </el-form-item>
      <el-form-item label="主图图片" prop="picPath">
        <!-- <el-input v-model="form.picPath" placeholder="请输入主图图片" /> -->
        <ImageUpload
          :value="form.picPath"
          :limit="1"
          @input="handleUploadSuccess"
        />
      </el-form-item>
      <el-form-item label="排序" prop="productSort">
        <el-input-number v-model="form.productSort" placeholder="请输入排序" />
      </el-form-item>
      <el-form-item label="商品总数量" prop="productTotal">
        <el-input-number
          v-model="form.productTotal"
          :min="0"
          placeholder="请输入商品总数量"
        />
      </el-form-item>
      <el-form-item label="产品内容" prop="detailHtml">
        <Editor
          :value="form.detailHtml"
          :height="400"
          @on-change="
            (e) => {
              form.detailHtml = e.html;
            }
          "
        />
      </el-form-item>

      <el-form-item label="商品规格" prop="specifications">
        <ul class="specifications-wrap">
          <li v-for="(item, idx) in specifications" :key="idx">
            <el-input
              class="input-name"
              v-model="item.name"
              placeholder="请输入规格名称"
            />
            <el-tag
              v-for="tag in item.values"
              :key="tag"
              closable
              size="large"
              :disable-transitions="false"
              @close="handleClose(tag, idx)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              class="input-new-tag"
              :autofocus="true"
              v-model="item.newTagValue"
              v-if="item.newTagVisible"
              @keyup.enter.native="handleInputConfirm(idx)"
              @blur="handleInputConfirm(idx)"
            >
            </el-input>
            <el-button
              v-else
              class="button-new-tag"
              size="small"
              @click="showInput(idx)"
              >+ 规格值</el-button
            >
            <el-button
              v-if="specifications.length > 1"
              type="text"
              icon="el-icon-delete"
              @click="deleteRow(idx)"
              >删除</el-button
            >
          </li>
        </ul>
        <el-button
          v-if="specifications.length < 2"
          type="text"
          icon="el-icon-circle-plus"
          @click="addRow"
          >添加一行</el-button
        >
      </el-form-item>

      <el-form-item label="商品内容" prop="goodsContent">
        <el-table
          ref="AdduceTableTableRef"
          :data="goodsList"
          border="border"
          stripe
          size="medium"
          style="width: 100%"
        >
          <el-table-column
            v-for="(item, index) in columns"
            :key="index"
            :prop="item.prop"
            align="center"
            :label="item.name"
          ></el-table-column>
          <el-table-column
            v-for="item in defaultColumns"
            :key="item.prop"
            :prop="item.prop"
            align="center"
            show-overflow-tooltip
            :label="item.name"
          >
            <template slot-scope="scope">
              <div class="lx-hidden" v-if="item.prop === 'goodsPrice'">
                <el-input-number
                  v-model="scope.row[item.prop]"
                  :controls="false"
                  :min="0"
                  style="width: 100%"
                  placeholder="请输入价格"
                />
              </div>
              <div class="lx-hidden" v-if="item.prop === 'goodsCount'">
                <el-input-number
                  v-model="scope.row[item.prop]"
                  style="width: 100%"
                  :step-strictly="true"
                  :controls="false"
                  placeholder="请输入库存"
                ></el-input-number>
              </div>
              <div class="" v-if="item.prop === 'picPath'">
                <ImageUpload
                  :value="item.picPath"
                  :isShowTip="false"
                  :showIcon="false"
                  listType="picture"
                  :limit="1"
                  @input="onChangeImg($event, scope.row)"
                />
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {
  getGoods,
  addGoods,
  updateGoods,
  saveRecord,
} from "@/api/goodsManage/goods";
import { listCategory } from "@/api/goodsManage/category";
import Editor from "@/components/Editor";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import ImageUpload from "@/components/ImageUpload";

const form = {
  id: null,
  goodsCode: null,
  goodsName: null,
  productCategoryId: null,
  productCategoryName: null,
  goodsPrice: null,
  picPath: null,
  productSort: null,
  productTotal: null,
  productSales: null,
  detailHtml: null,
  recommendStatus: "0",
  publishStatus: "0",
  delFlag: null,
  createTime: null,
  updateTime: null,
  createUserId: null,
  updateUserId: null,
  attrList: [],
  skuList: [],
};
// 规格添加
const addObj = {
  name: "",
  prop: "attr",
  newTagValue: "",
  newTagVisible: false,
  values: [],
};
// 参数字段
const defaultProps = {
  goodsPrice: "", // 价格 require：true
  goodsCount: "",
  picPath: "", // 封面图 require：true
};
// 默认表头
const defaultColumns = [
  {
    name: "价格(元)",
    prop: "goodsPrice",
    require: true,
    handlerType: 1, // 是否有其他操作
  },
  {
    name: "库存",
    prop: "goodsCount",
    require: true,
    handlerType: 1, // 是否有其他操作
  },
  {
    name: "封面图",
    prop: "picPath",
    require: true,
    handlerType: 1,
  },
];
export default {
  name: "EditGoods",
  components: {
    Editor,
    Treeselect,
    ImageUpload,
  },
  props: {
    id: {
      type: Number,
      default: 0,
    },
    visiable: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      // isOpen: false,
      form: this._.cloneDeep(form),
      // 表单校验
      rules: {
        goodsCode: [
          { required: true, trigger: "blur", message: "请输入商品编号" },
        ],
        goodsName: [
          { required: true, trigger: "blur", message: "请输入货品名称" },
        ],
        detailHtml: [
          { required: true, trigger: "blur", message: "请输入产品内容" },
        ],
        productCategoryId: [
          {
            required: true,
            message: "请选择商品类别",
            trigger: "change",
          },
        ],
      },
      // 规格/动态表头
      specifications: [this._.cloneDeep(addObj)],
      defaultProps: this._.cloneDeep(defaultProps), // 默认的表头参数
      defaultColumns: this._.cloneDeep(defaultColumns), // 默认表头
      mapList: [],
      goodsList: [],
      categoryList: [],
      imgList: [],
      skuList: [],
    };
  },
  computed: {
    title() {
      return this.id ? "编辑商品信息" : "添加商品信息";
    },
    // 动态表头
    columns() {
      let addObj = this._.cloneDeep(addObj);
      const arr = [];
      this.specifications.forEach((item, index) => {
        if (item.name) {
          item.prop = `attr${index}`;
          arr.push(item);
        }
      });
      return arr;
    },
  },
  mounted() {
    this.$nextTick(() => {
      if (this.id) {
        this.getGoodsInfo(this.id);
      }
    });

    this.getProductCategoryData();
  },

  watch: {
    specifications: {
      handler(currentList) {
        console.log("specifications", currentList);
        this.mapList = [];
        let i = 0;
        this.createList(currentList, i);
      },
      deep: true,
      immediate: true,
    },
    mapList: {
      handler(list) {
        if (list.length > 0) {
          const arr = [];
          list.forEach((item) => {
            if (item.child && item.child.length > 0) {
              item.child.forEach((citem) => {
                let obj = {
                  ...item,
                  ...citem,
                  ...this._.cloneDeep(defaultProps),
                };
                arr.push(obj);
              });
            } else {
              let obj = { ...item, ...this._.cloneDeep(defaultProps) };
              arr.push(obj);
            }
          });
          this.goodsList = arr;
          console.log("goodsList", this.goodsList);
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    handleUploadSuccess(files) {
      let data = [];
      files.forEach((item) => {
        data.push(item.name);
      });
      this.imgList = data;
    },
    // 规格----start
    handleClose(tag, idx) {
      let list = this.specifications[idx].values;
      list.splice(list.indexOf(tag), 1);
    },
    showInput(idx) {
      this.specifications[idx].newTagVisible = true;
    },
    handleInputConfirm(idx) {
      const newTagValue = this.specifications[idx].newTagValue;
      let list = this.specifications[idx].values;
      if (list.some((item) => item === newTagValue)) {
        this.$message.info("已有重复的值！");
        return false;
      }
      if (newTagValue) {
        list.push(newTagValue);
        this.specifications[idx].newTagValue = "";
      } else {
        this.specifications[idx].newTagValue = "";
      }
      this.specifications[idx].newTagVisible = false;
    },
    addRow() {
      this.specifications.push(this._.cloneDeep(addObj));
    },
    deleteRow(idx) {
      this.specifications.splice(idx, 1);
    },
    // 商品内容
    createList(currentList, i = 0) {
      if (currentList[i].name && currentList[i].values.length > 0) {
        let childValues = this.specifications[i + 1]
          ? this.specifications[i + 1].values
          : [];
        if (childValues.length > 0) {
          let child = [];
          childValues.forEach((item) => {
            let obj = {};
            obj[`attr${i + 1}`] = item;
            child.push(obj);
          });
          currentList[i].values.forEach((item) => {
            let obj = {};
            obj[`attr${i}`] = item;
            this.$set(obj, "child", child);
            this.mapList.push(obj);
          });
          i++;
        } else {
          currentList[i].values.forEach((item) => {
            let obj = {};
            obj[`attr${i}`] = item;
            this.$set(obj, "child", []);
            if (!this.mapList.some((citem) => citem[`attr${i}`] === item))
              this.mapList.push(obj);
          });
        }
      }
    },
    onChangeImg(item, row) {
      console.log("onChangeImg", item, row);
      if (item.length) {
        row.picPath = item[0].url;
      } else {
        row.picPath = "";
      }
    },
    // 规格----end

    // 获取商品详情
    getGoodsInfo(id) {
      getGoods(id).then((response) => {
        let info = response.data;

        info.picPath = info.picPath ? info.picPath.split(",") : [];
        this.imgList = info.picPath;
        Object.keys(this.form).forEach((key) => {
          this.form[key] = info[key];
        });
        let attrList = info.attrList;
        let attrKey = [];
        if (attrList.length) {
          this.specifications = [];
          attrList.forEach((item, index) => {
            attrKey[item.attrName] = "attr" + index;
            let obj = {
              name: item.attrName,
              prop: "attr",
              newTagValue: "",
              newTagVisible: false,
              values: item.attrValue ? item.attrValue.split(",") : [],
            };
            this.specifications.push(obj);
          });
        }

        let skuList = info.skuList;
        skuList.forEach((sku) => {
          let skuAttrData = JSON.parse(sku.goodsAttrs);
          let obj = { ...sku };
          skuAttrData.forEach((attr) => {
            for (var key in attr) {
              obj[attrKey[key]] = attr[key];
            }
          });
          this.skuList.push(obj);
        });
        console.log(this.skuList);
      });
    },

    // 商品分类
    getProductCategoryData() {
      listCategory().then((response) => {
        this.categoryList = this.handleTree(response.data, "id", "pid");
      });
    },

    /** 转换分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.categoryName,
        children: node.children,
      };
    },

    /** 提交按钮 */
    submitForm() {
      let attrList = [];
      let attrNameList = [];
      let skuList = [];

      this.specifications.forEach((item) => {
        if (item.name) {
          const obj = {
            attrName: item.name,
            attrValue: item.values ? item.values.join(",") : "",
            goodsld: null,
            id: null,
          };
          attrNameList[item.prop] = item.name;
          attrList.push(obj);
        }
      });
      this.goodsList.forEach((item, index) => {
        let attrNames = [];
        for (const key in item) {
          if (attrNameList[key]) {
            attrNames.push({
              [attrNameList[key]]: item[key],
            });
          }
        }

        let obj2 = {
          ...item,
          goodsAttrs: attrNames.length ? JSON.stringify(attrNames) : "",
        };
        // let obj2 = {
        //   goodsAttrs: attrNames.length ? JSON.stringify(attrNames) : "",
        //   goodsCount: item.goodsCount,
        //   goodsld: null,
        //   goodsPrice: item.goodsPrice,
        //   picPath: item.picPath,
        //   remark: "",
        // };
        skuList.push(obj2);
      });
      this.form.attrList = attrList;
      this.form.skuList = skuList;
      this.form.picPath = this.imgList ? this.imgList.join(",") : "";

      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.id) {
            saveRecord(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.$emit("confirm");
            });
          } else {
            saveRecord(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.$emit("confirm");
            });
          }
          setTimeout(() => {
            this.cancel();
          }, 300);
        }
      });
    },
    // 取消按钮
    cancel() {
      this.$emit("update:visiable", false);
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = this._.cloneDeep(form);
      this.resetForm("form");
    },
  },
};
</script>

<style scoped>
ul,
li {
  margin: 0;
  padding: 0;
}
.specifications-wrap li {
  margin-bottom: 15px;
}
.specifications-wrap li:last-child {
  margin-bottom: 0;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin: 0 10px;
  vertical-align: bottom;
}
.input-name {
  width: 150px;
  margin-right: 10px;
}
</style>
